﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Json;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace DomainName
{
    public class Json
    {
        ///<summary>
        /// 将对象序列化为JSON形式的字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string GetJSONSerialization<T>(T obj)
        {
            string jsonStr = string.Empty;
            if (obj != null)
            {
                DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
                MemoryStream ms = new MemoryStream();
                ser.WriteObject(ms, obj);
                jsonStr = Encoding.UTF8.GetString(ms.ToArray());
                ms.Close();
                string reg = @"\/Date((\d+)+\d+)\/";
                MatchEvaluator match = new MatchEvaluator(ConvertJsonDateToDateString);
                Regex regX = new Regex(reg);
                jsonStr = regX.Replace(jsonStr, match);
            }
            return jsonStr;
        }
        /// <summary>
        /// 将JSON字符串反序列化为对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="jsonString"></param>
        /// <returns></returns>
        public static T GetJSONDeserialize<T>(string jsonString)
        {
            string regStr = @"\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}";
            MatchEvaluator match = new MatchEvaluator(ConvertDateStringToJsonDate);
            Regex reg = new Regex(regStr);
            jsonString = reg.Replace(jsonString, match);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(T));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
            T obj = (T)ser.ReadObject(ms);
            return obj;
        }
        /// <summary>
        /// 将JSON时间格式转换为日期格式字符串
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        private static string ConvertJsonDateToDateString(Match m)
        {
            string result = string.Empty;
            DateTime dt = new DateTime(1970, 1, 1);
            dt = dt.AddMilliseconds(long.Parse(m.Groups[1].Value));
            dt = dt.ToLocalTime();
            result = dt.ToString("yyyy-MM-dd HH:mm:ss");
            return result;
        }
        /// <summary>
        /// 将日期格式字符串转换为JSON时间格式字符串
        /// </summary>
        /// <param name="m"></param>
        /// <returns></returns>
        private static string ConvertDateStringToJsonDate(Match m)
        {
            string result = string.Empty;
            DateTime dt = DateTime.Parse(m.Groups[0].Value);
            dt = dt.ToUniversalTime();
            TimeSpan ts = dt - DateTime.Parse("1970-01-01");
            result = string.Format(@"\/Date({0}+0800)\/", ts.TotalMilliseconds);
            return result;
        }
        /// <summary>
        /// 将对象序列化到文件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool SerializationToFile<T>(T obj, string filePath)
        {
            if ((!System.IO.File.Exists(filePath)) || obj == null)
            {
                return false;
            }
            else
            {
                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate);
                try
                {
                    BinaryFormatter bf = new BinaryFormatter();
                    bf.Serialize(fs, obj);
                }
                catch
                {
                    return false;
                }
                finally
                {
                    fs.Close();
                }
                return true;
            }
        }
        /// <summary>
        /// 从文件流中反序列化对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static T DeSerializationFromFile<T>(string filePath)
        {
            if (File.Exists(filePath))
            {
                FileStream fs = new FileStream(filePath, FileMode.Open);
                BinaryFormatter bf = new BinaryFormatter();
                T obj = (T)bf.Deserialize(fs);
                fs.Close();
                return obj;
            }
            else
            {
                return default(T);
            }
        }
    }
}